package org.example.top40;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class main19 {
    //二叉树的锯齿形层序遍历
    //输入：root = [3,9,20,null,null,15,7]
    //输出：[[3],[20,9],[15,7]]
    //思路：维护一个isLeft level变linkedList 一次addLast一次addFirst
    //记得isLeft=！isLeft
    public static void main(String[] args) {
        TreeNode root = builder();
        List<List<Integer>> res=new ArrayList<>();
        Deque<TreeNode> dq=new LinkedList<>();
        dq.add(root);
        boolean isLeft=true;
        while (!dq.isEmpty()){
            int size = dq.size();
            LinkedList<Integer> level = new LinkedList<>();
            for (int i = 0; i < size; i++) {
                TreeNode treeNode = dq.removeFirst();
                if(isLeft){
                    level.addLast(treeNode.val);
                }else {
                    level.addFirst(treeNode.val);
                }
                if(treeNode.left!=null){
                    dq.addLast(treeNode.left);
                }
                if(treeNode.right!=null){
                    dq.addLast(treeNode.right);
                }
            }
            res.add(level);
            isLeft=!isLeft;
        }
        System.out.println(res);
    }

/*    public static void main(String[] args) {
        TreeNode root = builder();
        List<List<Integer>> res=new ArrayList<>();
        Deque<TreeNode> dq=new LinkedList<>();
        dq.addLast(root);
        boolean isLeft=true;
        while(!dq.isEmpty()){
            int size = dq.size();
            LinkedList<Integer> level = new LinkedList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = dq.removeFirst();
                if(isLeft){
                    level.addLast(node.val);
                }else {
                    level.addFirst(node.val);
                }
                if(node.left!=null){
                    dq.addLast(node.left);
                }
                if(node.right!=null){
                    dq.addLast(node.right);
                }
            }
            res.add(level);
            isLeft=!isLeft;
        }
        System.out.println(res);
    }*/
    private static TreeNode builder(){
        TreeNode root = new TreeNode(3);
        TreeNode node1 = new TreeNode(9);
        TreeNode node2 = new TreeNode(20);
        TreeNode node3 = new TreeNode(15);
        TreeNode node4 = new TreeNode(7);
        root.left=node1;
        root.right=node2;
        node2.left=node3;
        node2.right=node4;
        return root;
    }
}
